import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/pic'
img_path = os.path.join(img_dir, 'friends.jpg')

spr = 3
spc = 4
spn = 0
plt.figure(figsize=[16, 12])

sep('load')
img = cv.imread(img_path, cv.IMREAD_UNCHANGED)
print(img.shape)
H, W, CH = img.shape

sep('pixel')
px = img[100, 100]
print(px)
blue = img[100, 100, 0]
print(blue)

img[100, 100] = [255, 255, 255]
print(img[100, 100])

sep('better pixel')
print(img.item(10, 10, 2))
img.itemset((10, 10, 2), 100)
print(img.item(10, 10, 2))

sep('property')
print(img.shape)
print(img.size)
print(img.dtype)

sep('ROI cp')
letter_s = img[106:139, 263:294]
my_show_img(letter_s, 'my_show_img', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
img[73:106, 263:294] = letter_s
my_show_img(img, 'friends cp', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('ROI mv')
dx, dy = 34, 46
letter_r = img[98:98 + dy, 47:47 + dx].copy()
letter_f = img[98:98+dy, 8:8+dx].copy()
img[98:98+dy, 8:8+dx] = letter_r
img[98:98+dy, 47:47+dx] = letter_f
my_show_img(img, 'friends mv', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('split and merge by cv')
b, g, r = cv.split(img)
my_show_img(b, 'b')
my_show_img(g, 'g')
my_show_img(r, 'r')
img_m = cv.merge((r, g, b))
my_show_img(img_m, 'merged')

sep('split and merge by numpy')
b2 = np.expand_dims(img[:, :, 0], 2)
g2 = img[:, :, 1:2]
r2 = np.expand_dims(img[:, :, 2], 2)
my_show_img(b2, 'b2')
my_show_img(g2, 'g2')
my_show_img(r2, 'r2')
img_m2 = np.concatenate((r2, g2, b2), axis=2)
my_show_img(img_m2, 'merged2')
